package org.web3j.utils;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 以太坊中代币数量的计量单位说明
 * (https://www.jianshu.com/p/b56552b1d1a0)
 */
public final class SeeleConvert {

    private SeeleConvert() {
    }

    public static BigInteger fromFan(String number, Unit unit) {
        return fromFan(new BigInteger(number), unit);
    }

    public static BigInteger fromFan(BigInteger number, Unit unit) {
        return number.divide(unit.getFanFactor());
    }

    public static BigInteger toFan(String number, Unit unit) {
        return toFan(new BigInteger(number), unit);
    }

    public static BigInteger toFan(BigInteger number, Unit unit) {
        return number.multiply(unit.getFanFactor());
    }

    public enum Unit {
        WEI("wei", 0),
        KWEI("kwei", 3),
        MWEI("mwei", 6),
        FAN("fan", 8),//SeeleToFan base feifan coin number
        GWEI("gwei", 9),
        SZABO("szabo", 12),
        FINNEY("finney", 15),
        ETHER("ether", 18),
        KETHER("kether", 21),
        METHER("mether", 24),
        GETHER("gether", 27);

        private String name;
        private BigInteger fanFactor;

        Unit(String name, int factor) {
            this.name = name;
            this.fanFactor = BigInteger.TEN.pow(factor);
        }

        public BigInteger getFanFactor() {
            return fanFactor;
        }

        @Override
        public String toString() {
            return name;
        }

        public static SeeleConvert.Unit fromString(String name) {
            if (name != null) {
                for (SeeleConvert.Unit unit : SeeleConvert.Unit.values()) {
                    if (name.equalsIgnoreCase(unit.name)) {
                        return unit;
                    }
                }
            }
            return SeeleConvert.Unit.valueOf(name);
        }
    }
}
